package com.litchi.service;

import com.litchi.spring.BeanPostProcess;
import com.litchi.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author LitchiShell
 * @description:
 * @create 2022-04-17
 */
@Component
public class LitchiBeanPostProcess implements BeanPostProcess {
    @Override
    public Object postProcessBeforeInitialization(String beanName, Object bean) {
        if ("userService".equals(beanName)) {
            System.out.println("postProcessBeforeInitialization");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(String beanName, Object bean) {
        if ("userService".equals(beanName)) {
            System.out.println("postProcessAfterInitialization");
            Object proxyObject = Proxy.newProxyInstance(LitchiBeanPostProcess.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("切面逻辑");
                    Object invoke = method.invoke(bean, args);
                    System.out.println("切面逻辑");
                    return invoke;
                }
            });
            return proxyObject;
        }
        return bean;
    }
}
